<template>
	<view>
		<view class="bc-navbar">
			<navbar :isHome="true"></navbar>
		</view>
		<view class="topContent">
			<view class="notice">
				<u-notice-bar :text="'准备好与同学分享您的奇思妙想了吗？联系作者 QQ：1341251971 微信公众号：baage-cn'" 
					mode="closable" speed="100"
					bgColor="#FFF"
					color="#b0b0b0"
				></u-notice-bar>
			</view>
			<view class="ad">
				<u-swiper
					:list="adList"
					keyName="image"
					showTitle
					:autoplay="true"
					:interval="5000"
					 height="380rpx"
					circular
					@click="clickSwiper"
				></u-swiper>
			</view>
			<view class="hot">
				<view class="left">
					<u--image src="http://8.140.251.165:9000/baage-campus/hot.png" width="130rpx" height="130rpx"></u--image>
				</view>
				<view class="right">
					<swiper v-if="hotList.length != 0" class="swiper" circular :vertical="true" :autoplay="true" :duration="2000" height="150rpx">
						<view  v-for="(item,index) in hotList">
							<swiper-item>
								<view @click="goDetail(item.id)">
									<u--text :text="item.abstractContent" :lines="2" :size="14" color="#ff6b6d"></u--text>
								</view>
							</swiper-item>
						</view>
					</swiper>
					<view v-else>
						<text>暂时没有热帖，赶快发帖吧~</text>
					</view>
				</view>
			</view>
		</view>
		<view class="category">
			<view class="tab" >
				  <u-sticky bgColor="#fff">
					<u-tabs :list="categoryList" :current="currentTab" @change="changeTab()"
						itemStyle="padding-left: 15rpx; height: 34px; font-weight: 600;"
					></u-tabs>
				  </u-sticky>
			</view>
			<view class="content"  :style="'height:' + listHeight + 'px'" @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd">
				<scroll-view :scroll-y="scrollY" :style="'height:' + listHeight + 'px'" @scrolltolower='loadMore'
					:refresher-enabled="enabledRefresher" :refresher-triggered="triggered" refresher-background="#FFF" :refresher-threshold="100" 
					@refresherrefresh="onRefresh" @refresherrestore="onRestore"
				>
					<view style="padding-bottom: 8rpx;">
						<view v-if="postingList.length != 0"  @scroll="onPageScroll">
							<post-item v-for="(item,index) in postingList" :key="item.id" :posting="item"></post-item>
							<view>
								<u-loadmore :status="loadingStatus"
								        :loading-text="loadingText" 
								        :loadmore-text="loadmoreText" 
								        :nomore-text="nomoreText" 
										line 
										lineColor="#d3dbe5"
										color="#6b6b6b"
								 />
							</view>
						</view>
						<view v-else style="padding-top: 80rpx; padding-bottom: 10rpx;">
							<view v-if="isLoading">
								<loading></loading>
							</view>
							<view v-else>
								<u-empty
								    mode="list"
									text="空空如也,到别处看看吧~"
								></u-empty>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</view>
	</view>
</template>

<script>
	import navbar from '@/components/navbar/navbar.vue'
	import postItem from '@/components/post-item/post-item.vue'
	import loading from '@/components/loading/loading.vue'
	
	import { listAllCategory } from '@/apis/category.js'
	import { listHotPosting, listPosting } from '@/apis/posting.js'
	
	import { mapState } from 'vuex'
	
	export default {
		components: {
			navbar,
			postItem,
			loading
		},
		data() {
            return {
				// 下拉刷新
				enabledRefresher: true,
				triggered: false,
				// 页面滚动
				scrollTop: 0, // 页面滚动高度
				scrollY: false, // 是否允许滚动
				startX: '', // 触摸起始点横坐标
				startY: '',
				deltaX: '',
				deltaY: '',
				// 加载更多
				isLoading: false, 
				loadingStatus: "loadmore",
				loadingText: '努力加载中',
				loadmoreText: '轻轻上拉',
				nomoreText: '没有更多了~',
				// tab
				currentTab: 0,
				// 计算高度
				topHeight: 0,
				listHeight: 0,
				// 业务数据
				postingList: [],
				hotList: [],
				categoryList: [{
					name: '最新'
				}],
				postingCount: -1,
				// 查询条件
				queryPosting: {
					pageNum: 1,
					pageSize: 10,
					orderByColumn: 'createTime',
					isAsc: 'desc',
					categoryId: '',
					userId: '',
					search: ''
				},
                adList: [{
                    image: 'http://8.140.251.165:9000/baage-campus/ad/ad1.png',
                    title: '准备好与同学分享您的奇思妙想了吗？'
                },{
                    image: 'http://8.140.251.165:9000/baage-campus/ad/ad2.jpg',
                    title: '猫脸山茶，欢迎各位品尝'
                }],
            }
		},
		methods: {
			/** 修改分类tab**/
			changeTab({index}) {
				this.currentTab = index;
				if (index != 0) {
					this.queryPosting.categoryId=this.categoryList[index].id;
				} else {
					this.queryPosting.categoryId = ''
				}
				this.doListPosting();
			},
			/** 查询帖子 **/
			doListPosting() {
				let _this = this;
				_this.isLoading = true;
				_this.postingList = [];
				_this.queryPosting.pageNum = 1;
				listPosting(_this.queryPosting).then( res => {
					_this.postingList = res.rows;
					_this.postingCount  = res.total;
					if (res.total <= 10) {
						_this.loadingStatus = "nomore";
					}
				}).finally(r => {
					_this.isLoading = false
				})
			},
			// 热门帖子
			doListHotPosting() {
				let _this = this;
				listHotPosting().then( res => {
					_this.hotList = res.rows;
				})
			},
			/** 加载更多帖子 **/
			loadMore() {
				let _this = this;
				if (_this.postingCount != -1 &&  _this.queryPosting.pageNum * _this.queryPosting.pageSize >= _this.postingCount) {
					_this.loadingStatus = "nomore";
					return;
				}
				_this.loadingStatus = "loading";
				_this.queryPosting.pageNum = _this.queryPosting.pageNum + 1;
				listPosting(_this.queryPosting).then( res => {
					_this.postingList = [..._this.postingList,...res.rows];
					_this.postingCount  = res.total;
				}).finally(r => {
					_this.loadingStatus = "loadmore";
				})
			},
			/** 列表滚动沾满屏幕 **/
			onPageScroll(event) {
				this.scrollTop = event.scrollTop // 更新页面滚动高度
				if (this.scrollTop + 3 >= this.topHeight) {
					this.scrollY = true;
					this.enabledRefresher = false;
				} else {
					this.scrollY = false;
					this.enabledRefresher = true;
				}
			},
			/** 设置看列表高度**/
			async setListHeight() {
				let that = this;
				// 页面高度
				let sysInfo = uni.getSystemInfoSync();
				let winHeight = sysInfo.windowHeight;
				// header 高度
				let headerHeight = 0;
				let headerView = uni.createSelectorQuery().select(".bc-navbar");
				headerView.boundingClientRect(data=>{
					headerHeight = data.height;
				}).exec(function(res) {
					that.listHeight = winHeight - headerHeight;
					let tabHeight = 0;
					let tabView =  uni.createSelectorQuery().select(".tab");
					tabView.boundingClientRect(data => {
						tabHeight = data.height;
					}).exec(function(res) {
						that.listHeight = that.listHeight - tabHeight;
					})	
				});
			},
			/** 设置上部分内容高度 **/
			async setTopHeight() {
				let that = this;
				let topHeight = 0;
				let topHeightView = uni.createSelectorQuery().select(".topContent");
				topHeightView.boundingClientRect(data=>{
					topHeight = data.height;
				}).exec(function(res) {
					that.topHeight = topHeight;
				});
			},
			/** 滑动屏幕 **/
			touchStart(event) {
				// 记录触摸起始点的横坐标
				this.startX = event.touches[0].clientX;
				this.startY = event.touches[0].clientY;
			},
			touchMove(event) {
				// 计算滑动距离
				const currentX = event.touches[0].clientX;
				const currentY = event.touches[0].clientY;
				this.deltaX = currentX - this.startX;
				this.deltaY = currentY - this.startY;
			},
			touchEnd() {
				if (this.deltaY > 70 || this.deltaY < -70) {
					return;
				}
				// 判断滑动方向
				if (this.deltaX > 70) {
					let ctab = ((this.currentTab + this.categoryList.length) - 1) % this.categoryList.length;
					this.changeTab({index: ctab})
				} else if (this.deltaX < -70) {
					let ctab = ((this.currentTab + this.categoryList.length) + 1) % this.categoryList.length;
					this.changeTab({index: ctab})
				}
				this.startX = ''
				this.startY = ''
				this.deltaX = ''
				this.deltaY = ''
			},
			// 跳转详情
			goDetail(id) {
				uni.navigateTo({
					url: '/pages/detail/detail?id=' + id
				})
			},
			/** 下拉刷新 **/
			onRefresh() {
				if (this._freshing) return;
				this.triggered = true;
				this._freshing = true;
				this.doListPosting();
				this.triggered = false;
				this._freshing = false;
				this.doListHotPosting();
			},
			onRestore() {
				this.triggered = 'restore'; // 需要重置
				console.log("onRestore");
			},
			clickSwiper(index) {
				console.log(index)
			}
		},
		onLoad() {
			let _this = this;
			listAllCategory().then( res => {
				_this.categoryList.push(...res.data.categoryList)
			});
			this.doListHotPosting();
			this._freshing = false;
			this.triggered = true;
		},
		onShow() {

		},
		// onLoad 和 onShow 无法获取 DOM 元素信息
		onReady() {
			this.setListHeight();
			this.setTopHeight();
		},
		onPullDownRefresh() {
			let _this = this;
			console.log('refresh');
			_this.doListPosting();
		}
	}
</script>

<style scoped>
	
	.content {
		padding: 0 20rpx;
	}
	
	.hot {
		display: flex; 
		align-items: center;
		width: 720rpx;
		margin: 20rpx 15rpx;
		border-radius: 2%;
	}
	
	.hot .left {
		width: 150rpx;
		margin: 0 10rpx;
	}
	
	.hot .right {
		width: 570rpx;
		height: 80rpx;
		padding: 0 10rpx;
	}
	
	.hot .right swiper {
		height: 130rpx !important;
	}
</style>
